package com.happypets.filter;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import com.happypets.services.PetService;
import com.happypets.servicesImpl.PetServiceImpl;

public class SearchFilter implements Filter {

	public SearchFilter() {
	}

	public void destroy() {
	}
	
	/**
	 * 此过滤器是为了正常显示侧边的搜索框而设置的  删除
	 */
	
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		
		System.out.println("------searchFilter start");

		HttpServletRequest req = (HttpServletRequest) request;
		PetService service = new PetServiceImpl();

		HttpSession session = req.getSession();

		String kind = req.getParameter("kind");

		System.out.println("searchKind = " + kind);

		if (kind == null || kind.equals("null")) {
			kind = "1";
		}

		/**
		 * 防止每次进入就加载
		 */
		if(session.getAttribute("searchFlag") == null){
			String sql = "select animal_shape,count(*) from (select a.* from animalsinfo a where a.bigcategoryid = " + kind
					+ ") group by animal_shape ";

			System.out.println("search sql 1 " + sql);

			List<Map<String, String>> shape = (List<Map<String, String>>) service.query(sql);

			sql = "select animal_color,count(*) from (select a.* from animalsinfo a where a.bigcategoryid = "+kind+") group by animal_color";

			List<Map<String, String>> color = (List<Map<String, String>>) service.query(sql);

			sql = "select b.name,c.* from ( select smallcategoryid,count(*) from (select a.* from animalsinfo a where a.bigcategoryid = "+kind+") "
					+ "group by smallcategoryid ) c left join smallcategory b on c.smallcategoryid = b.smallcategory ";
			
			List<Map<String, String>> category = (List<Map<String, String>>) service.query(sql);
			
			session.setAttribute("shapes",shape);
			session.setAttribute("categories", category);
			session.setAttribute("colors", color);
			
			System.out.println("已加载");
		}
		
		// 放到代码后面
		session.setAttribute("searchFlag", "yes");
		
		

		chain.doFilter(req, response);
	}

	public void init(FilterConfig fConfig) throws ServletException {
	}

}
